//
//  NetWorkingManager.swift
//  NewDelivery
//
//  Created by 天下宅 on 2016/11/4.
//  Copyright © 2016年 天下宅. All rights reserved.
//

import UIKit
import SwiftyJSON
import SVProgressHUD
//let thisURLString = "https://api.lrztx.com/index.php"
let fristUrl = "https://1.5.lrztx.com/index.php"


enum WKNetWorkState {
    case Success
    case Faild(String)
}


class NetWorkingManager: NSObject {
    
    var realUrl:String = "https://1.5.lrztx.com/index.php"
    
    static let shared : NetWorkingManager = {
        let _networkManager = NetWorkingManager()
        return _networkManager
    }()
    
//  HTTPS
    let selfSignedHosts = ["1.5.lrztx.com","api.lrztx.com"]
    
    private static func postRequest(parmars:inout [String: Any],hintStr:String?,block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
//        SVProgressHUD.dismiss()
        if hintStr != nil {
            SVProgressHUD.show(withStatus: hintStr!)
        }
        
        parmars["datatype"] = "json"
        parmars["ctrl"] = "psuser"
        let action = parmars["action"] as? String
        if (action != nil)
        {
            if action != "applogin" && action != "findpwd"
            {
                let userinfo = WKUserInfo.shared
                parmars["accesstoken"] = userinfo.token//放入token
            }
//            print(userinfo.token)
        }
        
        print(parmars)

        
//        let session: URLSession = URLSession.shared

        //HTTPS
        let config = URLSessionConfiguration.default
        let session: URLSession = URLSession.init(configuration: config, delegate: NetWorkingManager.shared, delegateQueue: OperationQueue.main)
        //2.根据会话对象创建task
        let url: URL = URL.init(string: NetWorkingManager.shared.realUrl)!
        //3.创建可变的请求对象
        var request: URLRequest = URLRequest(url: url)
        //4.修改请求方法为POST
        request.httpMethod = "POST"
        request.httpBody = NetWorkingManager.query(parameters: parmars).data(using: String.Encoding.utf8)
        let dataTask = session.dataTask(with: request) { (data, res, err) in
            if err == nil
            {
                if data != nil
                {
                    let json = JSON.init(data: data!)
                    let status = json.dictionaryValue["error"]!.boolValue
                    if status
                    {
                        //有问题
                        DispatchQueue.main.async {
                            
                            let msg = json.dictionaryValue["msg"]
                            if msg == "身份标识失效"
                            {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: QUIT), object: nil, userInfo: nil)
                            }
                            else
                            {
                                block(WKNetWorkState.Faild(json.dictionaryValue["msg"]?.string ?? "网络连接失败"),nil)
                            }
                            
                        }

                    }
                    else
                    {
                        DispatchQueue.main.async {
                            block(WKNetWorkState.Success,json.dictionaryValue["msg"])
                        }
                    }
                }
            }
            else
            {
                print(err!.localizedDescription)
            }
            if action != "applogin"
            {
                SVProgressHUD.dismiss()
            }
            
            
        }
        dataTask.resume()
    }
    
    static func login(WithUName name:String, pwd:String, hintStr:String?, block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
        var parmars = [String: Any]()
        parmars["uname"] = name
        parmars["ctrl"] = "psuser"
        parmars["pwd"] = pwd.md5
        parmars["action"] = "applogin"
        parmars["pushid"] = WKGTPusherManager.shard.pushKey
        parmars["channelid"] = "ios_Appstore"

        self.postRequest(parmars: &parmars, hintStr: hintStr, block: block)
    }
    
    static func getNewOrder(page:UInt, hintStr:String?, block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
        var parmars = [String: Any]()

        parmars["action"] = "waitorder"
        parmars["page"] = page
        self.postRequest(parmars: &parmars, hintStr: hintStr, block: block)
    }
    
    
    static func getMyOrder(page:UInt, hintStr:String?, block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
        var parmars = [String: Any]()

        parmars["action"] = "getmyorder"
        parmars["page"] = page
        self.postRequest(parmars: &parmars, hintStr: hintStr, block: block)
    }
    
    //默认七天
    static func getFinishOrder(startDate:String, endDate:String, page:UInt, hintStr:String?, block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
        var parmars = [String: Any]()
        parmars["action"] = "getoverorder"
        

        parmars["startdate"] = startDate
        parmars["enddate"] = endDate
        parmars["page"] = page
        self.postRequest(parmars: &parmars, hintStr: hintStr, block: block)
    }
    
    static func getOrderDetail(WithID orderID: String, hintStr:String?, block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
        var parmars = [String: Any]()

        parmars["action"] = "appbuyerone"
        parmars["orderid"] = orderID        
        self.postRequest(parmars: &parmars, hintStr: hintStr, block: block)
    }
    
    
    static func handleOrder(WithID orderID: String,dotType:String, hintStr:String?, block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
        var parmars = [String: Any]()
        parmars["action"] = "ordercontrol"
        parmars["orderid"] = orderID
        parmars["dotype"] = dotType

        self.postRequest(parmars: &parmars, hintStr: hintStr, block: block)
    }
    
    static func updateLocation(_ location:CLLocationCoordinate2D, block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
        var parmars = [String: Any]()
        parmars["action"] = "location"
        parmars["lat"] = location.latitude
        parmars["lng"] = location.longitude
        self.postRequest(parmars: &parmars, hintStr: nil, block: block)
    }
    
    static func findpasswd(WithPhone phone:String,code:String,newpwd:String,hintStr:String?, block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
        var parmars = [String: Any]()
        parmars["action"] = "findpwd"
        parmars["phone"] = phone
        parmars["newpwd"] = newpwd
        parmars["surepwd"] = newpwd
        parmars["code"] = code
        self.postRequest(parmars: &parmars, hintStr: hintStr, block: block)
    }
    
    static func logout(_ hintStr:String?, block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
        var parmars = [String: Any]()
        parmars["action"] = "apploginout"

        self.postRequest(parmars: &parmars, hintStr: hintStr, block: block)
    }
    
    static func getIncome(_ startDate:String,endDate:String,hintStr:String?, block:@escaping (WKNetWorkState,JSON?) -> Void)
    {
        var parmars = [String: Any]()
        parmars["action"] = "psyapptj"
        parmars["startday"] = startDate
        parmars["endday"] = endDate
        
        self.postRequest(parmars: &parmars, hintStr: hintStr, block: block)
    }
    
    static func getUrl()
    {
        //HTTPS
        let config = URLSessionConfiguration.default
        let session: URLSession = URLSession.init(configuration: config, delegate: NetWorkingManager.shared, delegateQueue: OperationQueue.main)
        //2.根据会话对象创建task
        let url: URL = URL.init(string:fristUrl)!
        //3.创建可变的请求对象
        var request: URLRequest = URLRequest(url: url)
        //4.修改请求方法为POST
        request.httpMethod = "POST"
        
        let dict = Bundle.main.infoDictionary!
        print(dict)
        let versionStr:String = dict["CFBundleShortVersionString"] as! String
        let arr = versionStr.components(separatedBy: ".")
        let count:UInt = UInt(arr.count)
        
        var versionNum:UInt = 0
        var i:UInt = 0
        for str in arr {
            var temp:UInt = 1;
            var ii:UInt = i;
            while (count - 1 - ii) > 0 {
                temp *= 10
                ii += 1
            }
            i += 1;
            let this = UInt((str as NSString).integerValue) * temp
            versionNum += this
        }
        versionNum *= 10
        print(versionNum)
        
        
        var parmars = [String:Any]()
        parmars["action"] = "checkupdate";
        parmars["ctrl"] = "app";
        parmars["datatype"] = "json"
        parmars["apptype"] = "psuer"
        parmars["version"] = versionNum
        
        request.httpBody = NetWorkingManager.query(parameters: parmars).data(using: String.Encoding.utf8)
        
        SVProgressHUD.show(withStatus: "加载数据中")
        let dataTask = session.dataTask(with: request) { (data, res, err) in
//            SVProgressHUD.dismiss()
            if err == nil
            {
                if data != nil
                {
                    let json = JSON.init(data: data!)
                    print(json)
                    let status = json.dictionaryValue["error"]!.boolValue
                    if status
                    {
                        //有问题
                        DispatchQueue.main.async {
                            
                            let msg = json.dictionaryValue["msg"]
                            if msg == "身份标识失效"
                            {
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: QUIT), object: nil, userInfo: nil)
                            }
                        }
                        
                    }
                    else
                    {
                        NetWorkingManager.shared.realUrl = json.dictionaryValue["msg"]!.dictionaryValue["siteurl"]!.stringValue
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: URLUpdate), object: nil, userInfo: nil)
                        print(NetWorkingManager.shared.realUrl)
                    }
                }
            }
            else
            {
                print(err!.localizedDescription)
            }
            
            
        }
        dataTask.resume()
    }
    
}



//MARK  HTTPS
extension NetWorkingManager:URLSessionDelegate
{
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust && self.selfSignedHosts.contains(challenge.protectionSpace.host) {
            print("服务器验证")
            let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
            completionHandler(.useCredential, credential)
        }
    }
}
//MARK 参数转换为HTTPbody
extension NetWorkingManager
{
    static func query(parameters: [String: Any]) -> String {
        var components: [(String, String)] = []
        
        for key in parameters.keys.sorted(by: <) {
            let value = parameters[key]!
            components += wkQueryComponents(key:key, value)
        }
        
        return (components.map { "\($0)=\($1)" } as [String]).joined(separator: "&")
    }
    
    //MARK: 这一段代码是抄的Alamofire的
    internal static func wkQueryComponents(key: String, _ value: Any) -> [(String, String)] {
        var components: [(String, String)] = []
        
        if let dictionary = value as? [String: AnyObject] {
            for (nestedKey, value) in dictionary {
                components += wkQueryComponents(key:"\(key)[\(nestedKey)]", value)
            }
        } else if let array = value as? [AnyObject] {
            for value in array {
                components += wkQueryComponents(key:"\(key)[]", value)
            }
        } else {
            components.append((wkEscape(string:key), wkEscape(string:"\(value)")))
        }
        
        return components
    }
    internal static func wkEscape(string: String) -> String {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="
        
        var allowedCharacterSet = CharacterSet.urlQueryAllowed
        allowedCharacterSet.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)
        var escaped = ""
        if #available(iOS 8.3, OSX 10.10, *) {
            escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
        } else {
            let batchSize = 50
            var index = string.startIndex
            
            while index != string.endIndex {
                let startIndex = index
                let endIndex = string.index(index,offsetBy: batchSize, limitedBy: string.endIndex)!
                let range = startIndex..<endIndex
                
                let substring = string.substring(with:range)
                
                escaped += string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring
                
                index = endIndex
            }
        }
        
        return escaped
    }

}
